<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <span>用户登录</span>
        </div>
      </template>
      <p>
        <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm"
          :size="formSize" status-icon>
          <el-form-item label="账号" prop="Name">
            <el-input v-model="form.Name" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item label="密码" prop="Pass">
            <el-input v-model="form.Pass" show-password placeholder="请输入密码" />
          </el-form-item>
          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="form.captcha" placeholder="请输入验证码"></el-input>
            <canvas style="margin-top: 10px;" ref="captchaCanvas" @click="refreshCaptcha"></canvas>
            <el-button link type="primary" @click="refreshCaptcha">看不清,换一张</el-button>
          </el-form-item>
        </el-form>
      </p>
      <template #footer>
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            登录
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        </el-form-item>
      </template>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import { useCounterStore } from '@/stores/counter.ts'
import { axios } from '@/axios/axiosHelp'

const store = useCounterStore()
const router = useRouter()
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()

const form = reactive({
  Name: '',
  Pass: '',
  captcha: ''
})

// 验证码 canvas 引用
const captchaCanvas: any = ref(null);
// 当前生成的验证码
const captchaCode: any = ref('');

// 生成随机验证码
const generateCaptcha = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let code = '';
  for (let i = 0; i < 4; i++) {
    code += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  captchaCode.value = code;
};

// 绘制验证码到 canvas 上
const drawCaptcha = () => {
  const canvas = captchaCanvas.value;
  const ctx = canvas.getContext('2d');
  canvas.width = 120;
  canvas.height = 40;

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 设置背景颜色
  ctx.fillStyle = '#ffffff'; // 使用白色背景，增强对比度
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 减少干扰线数量
  for (let i = 0; i < 2; i++) {
    ctx.beginPath();
    ctx.strokeStyle = '#cccccc'; // 使用浅灰色，降低干扰度
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 减少干扰点数量
  for (let i = 0; i < 10; i++) {
    ctx.beginPath();
    ctx.fillStyle = '#cccccc'; // 使用浅灰色，降低干扰度
    const x = Math.random() * canvas.width;
    const y = Math.random() * canvas.height;
    ctx.arc(x, y, 1, 0, 2 * Math.PI);
    ctx.fill();
  }

  // 绘制验证码字符
  const fontSize = 28; // 增大字体大小
  ctx.font = `${fontSize}px Arial`;
  ctx.textBaseline = 'middle'; // 设置文本基线为中间
  for (let i = 0; i < captchaCode.value.length; i++) {
    ctx.fillStyle = '#333333'; // 使用深灰色，增强对比度
    ctx.fillText(
      captchaCode.value[i],
      15 + i * fontSize,
      canvas.height / 2
    );
  }
};

// 生成随机颜色
const getRandomColor = () => {
  const r = Math.floor(Math.random() * 256);
  const g = Math.floor(Math.random() * 256);
  const b = Math.floor(Math.random() * 256);
  return `rgb(${r},${g},${b})`;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  drawCaptcha();
  form.captcha = '';
};

// 方法
const submitForm = async (formEl: FormInstance | undefined) => {
  if (form.captcha.toLowerCase() != captchaCode.value.toLowerCase()) {
    ElMessage.error('验证码错误,请重新输入')
    refreshCaptcha()
    return
  }

  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      window.localStorage.setItem("token", "");
      axios.get('http://localhost:7081/api/User/Login', { params: form }).then((res => {
        if (res.data.code == 200) {
          ElMessage.success('登录成功!')
          console.log(store.currentUser.userId, '66666')
          store.currentUser.userId = res.data.data.userId
          store.currentUser.name = res.data.data.name
          store.currentUser.pass = res.data.data.pass
          store.currentUser.departmentId = res.data.data.departmentId
          store.currentUser.powerId = res.data.data.powerId
          // 登录判定
          // 登录成功，写JWT的 token到本地
          localStorage.token = res.data.msg

          router.push('/Navigation')
          // router.push('/MainView')
        }
        if (res.data.code == 201) {
          ElMessage.error(res.data.msg)
        }
        if (res.data.code == 202) {
          ElMessage.error(res.data.msg)
        }
      }))
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

// 验证
const rules = reactive<FormRules>({
  Name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  Pass: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  captcha: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ]
})

// 组件挂载时生成初始验证码
onMounted(() => {
  generateCaptcha();
  drawCaptcha();
});
</script>

<style scoped>
/* 动态背景样式 */
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(-45deg, #454b8b, #19ba34, #8ba756, #b26882);
  background-size: 400% 400%;
  animation: gradient 5s ease infinite;
}

@keyframes gradient {
  0% {
    background-position: 0% 50%;
  }

  50% {
    background-position: 100% 50%;
  }

  100% {
    background-position: 0% 50%;
  }
}

/* 登录卡片样式 */
.login-card {
  width: 480px;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
  padding: 20px;
  background-color: #fff;
}

/* 卡片头部样式 */
.card-header {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

/* 表单元素样式 */
.demo-ruleForm .el-form-item {
  margin-bottom: 20px;
}

.demo-ruleForm .el-input {
  border-radius: 5px;
  border: 1px solid #ccc;
  padding: 8px;
}

.demo-ruleForm .el-input:focus {
  border-color: #71b7e6;
  box-shadow: 0 0 5px rgba(113, 183, 230, 0.5);
}

/* 验证码区域样式 */
canvas {
  cursor: pointer;
  border: 1px solid #ccc;
  vertical-align: middle;
  margin-left: 10px;
  border-radius: 5px;
}

/* 按钮样式 */
.el-form-item .el-button {
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
}

.el-form-item .el-button.primary {
  background-color: #71b7e6;
  border-color: #71b7e6;
}

.el-form-item .el-button.primary:hover {
  background-color: #5fa7d8;
  border-color: #5fa7d8;
}

.el-form-item .el-button.link {
  color: #71b7e6;
}

.el-form-item .el-button.link:hover {
  color: #5fa7d8;
}
</style>